const {
    app,
    BrowserWindow,
    ipcMain
} = require('electron')
const electron = require('electron')
const {
    requireModule
} = require('./background-util')
const path = require('path')
process.env['ELECTRON_DISABLE_SECURITY_WARNINGS'] = 'true'
requireModule()
const {
    spawn
} = require('child_process');

// require('./updateMain')()
const updateFunc = require('./update')
const request = require('./utils/request')

let win
let electronScreen

function createWindow() {
    const config = {
        hostname: '118.144.87.37', // test
        port: 13083, // test
        path: '/runtime/data/selectData.action',
        method: "POST",
        headers: {
            "Content-Type": "application/json;charset=utf-8",
            "Content-Length": Buffer.byteLength(JSON.stringify({
                "deviceType": "0"
            }))
        },
        timeout: 60000,
        webPreferences: {
            nodeIntegration: true
        }
    };
    // request(config, JSON.stringify({"deviceType": "0"}))
    //     .then(res => {
    //         let data = JSON.parse(res).data
    //         // picName 包名 zipUrl 包地址 projectId 项目id
    //         updateFunc(data[0].picName, data[0].zipUrl, (err) => {
    //             if (err) {
    //                 throw new Error(err)
    //             }
    //             win = new BrowserWindow({
    //                 show: false,
    //                 width: 1350,
    //                 height: 900,
    //                 // minWidth: 900,
    //                 // minHeight: 600,
    //                 backgroundColor: '#f0eff4',
    //                 webPreferences: {
    //                     webSecurity: false,
    //                     defaultFontFamily: {
    //                         standard: 'Microsoft YaHei'
    //                     },
    //                     defaultEncoding: 'utf-8',
    //                     // https://electronjs.org/docs/faq
    //                     nodeIntegration: true,
    //                     preload: path.resolve(__dirname, './jsSDK/index.js')
    //                 }
    //             })
    //
    //
    //             win.once('ready-to-show', () => {
    //                 win.show()
    //                 win.focus()
    //             })
    //             // 是否显示控制台
    //             // win.webContents.openDevTools()nm
    //             let url = require('url').format({
    //                 protocol: 'file',
    //                 slashes: true,
    //                 pathname: path.join(__dirname, 'index.html')
    //             })
    //             win.loadURL(path.join('file://', path.resolve(__dirname), 'src', data[0].picName, '/index.html'))
    //             // win.loadURL(url)
    //
    //             // 关闭当前窗口后触发
    //             win.on('closed', () => {
    //                 // proxy.kill()
    //                 win = null
    //                 console.log('结束所有进程')
    //             })
    //             win.on('error', (err) => {
    //                 throw new Error(err)
    //             })
    //         })
    //     })

    win = new BrowserWindow({
        show: false,
        width: 1350,
        height: 900,
        // minWidth: 900,
        // minHeight: 600,
        backgroundColor: '#f0eff4',
        webPreferences: {
            webSecurity: false,
            defaultFontFamily: {
                standard: 'Microsoft YaHei'
            },
            defaultEncoding: 'utf-8',
            // https://electronjs.org/docs/faq
            nodeIntegration: true,
            preload: path.resolve(__dirname, './jsSDK/index.js')
        }
    })


    win.once('ready-to-show', () => {
        win.show()
        win.focus()
    })
    // 是否显示控制台
    // win.webContents.openDevTools()nm
    let url = require('url').format({
        protocol: 'file',
        slashes: true,
        pathname: path.join(__dirname, 'src/menu', 'index.html')
    })
    // win.loadURL(path.join('file://', path.resolve(__dirname), 'src', data[0].picName, '/index.html'))
    win.loadURL(url)

    // 关闭当前窗口后触发
    win.on('closed', () => {
        // proxy.kill()
        win = null
        console.log('结束所有进程')
    })
    win.on('error', (err) => {
        throw new Error(err)
    })

    ipcMain.on('changeUrl', (event, arg) => {
        console.log('url:', arg)
        win.loadURL(path.join('file://', arg, '/index.html'))
    })
    ipcMain.on('goBackHome', (event, arg) => {
        console.log('url:', arg)
        win.loadURL(url)
    })
}

// app.on('ready', createWindow)
app.on('ready', () => {
    electronScreen = electron.screen
    // childProcess()
})
// Quit when all windows are closed.
app.on('window-all-closed', function () {
    if (process.platform !== 'darwin') {
        app.quit()
    }
})

app.on('activate', function () {
    if (win === null) {
        createWindow()
    }
})

// 单实例
const gotTheLock = app.requestSingleInstanceLock()
if (!gotTheLock) {
    app.quit()
} else {
    app.on('second-instance', (event, commandLine, workingDirectory) => {
        // 当运行第二个实例时,将会聚焦到myWindow这个窗口
        if (win) {
            if (win.isMinimized()) win.restore()
            win.focus()
        }
    })
    // 创建 myWindow, 加载应用的其余部分, etc...
    app.on('ready', async () => {
        createWindow()
    })
}

// const { execFile } = require('child_process');
// const child = execFile('node', ['--version'], (error, stdout, stderr) => {
//     if (error) {
//         throw error;
//     }
//     console.log(stdout);
// });